package com.lou.springboot.controller.admin;

import com.lou.springboot.common.ResultVO;
import com.lou.springboot.common.ResultVOUtil;
import com.lou.springboot.entity.BlogCategory;
import com.lou.springboot.enums.ResultEnum;
import com.lou.springboot.service.BlogCategoryService;
import com.lou.springboot.utils.JsonUtils;
import com.lou.springboot.utils.PageUtil;
import com.lou.springboot.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin")
public class BlogCategoryController {
    private final static String blogCategoryRedisPrefix = "blog_category_";

    @Autowired
    private RedisOperator redisOperator;

    @Autowired
    private BlogCategoryService blogCategoryService;

    @GetMapping("/categories")
    public String categoryPage(HttpServletRequest request){
        request.setAttribute("path", "categories");
        return "admin/category";
    }

    /**
     * 文章分类列表
     * @param params
     * @return
     */
    @GetMapping("/categories/list")
    @ResponseBody
    public ResultVO list(@RequestParam Map<String, Object> params){
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        PageUtil pageUtil = new PageUtil(params);
        return ResultVOUtil.success(blogCategoryService.getBlogCategoryPage(pageUtil));
    }

    /**
     * 分类添加
     */
    @RequestMapping(value = "/categories/save", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO save(@RequestParam("categoryName") String categoryName,
                         @RequestParam("categoryIcon") String categoryIcon){
        if (StringUtils.isEmpty(categoryName)) {
            return ResultVOUtil.error(ResultEnum.CATEGORY_NAME_ERROR);
        }
        if (StringUtils.isEmpty(categoryIcon)) {
            return ResultVOUtil.error(ResultEnum.CATEGORY_ICON_ERROR);
        }
        if (blogCategoryService.saveBlogCategory(categoryName, categoryIcon)) {
            return ResultVOUtil.success();
        } else {
            return ResultVOUtil.error(ResultEnum.CATEGORY_NAME_REPEAT);
        }
    }

    /**
     * 分类删除（可批量删除）
     */
    @PutMapping("/categories/delete")
    @ResponseBody
    public ResultVO delete(@RequestBody Integer[] ids){
        if (ids.length < 1) {
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }

        if (blogCategoryService.deleteBatch(ids)){
            List<String> idsList = Arrays.asList(ids).stream().map(id -> blogCategoryRedisPrefix + id).collect(Collectors.toList());
            redisOperator.del(idsList);
            return ResultVOUtil.success();
        } else {
            return ResultVOUtil.error(ResultEnum.DELETE_FAILED);
        }
    }

    /**
     * 详情
     */
    @GetMapping("/categories/info/{categoryId}")
    @ResponseBody
    public ResultVO info(@PathVariable("categoryId") Integer categoryId){
        if (categoryId == null || categoryId < 1) {
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        String categoryKey = blogCategoryRedisPrefix + categoryId;

        String blogCategoryString = redisOperator.get(categoryKey);
        BlogCategory blogCategory;
        if (blogCategoryString != null) {
            blogCategory = JsonUtils.jsonToPojo(blogCategoryString, BlogCategory.class);
        } else {
            blogCategory = blogCategoryService.getBlogCategoryById(categoryId);
            redisOperator.set(categoryKey, JsonUtils.objectToJson(blogCategory));
        }

        return ResultVOUtil.success(blogCategory);
    }

    /**
     * 更新
     */
    @PutMapping("/categories/update")
    @ResponseBody
    public ResultVO update(@RequestParam Integer categoryId,
                           @RequestParam String categoryName,
                           @RequestParam String categoryIcon){
        if (categoryId == null || categoryId < 1) {
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        if (StringUtils.isEmpty(categoryName)) {
            return ResultVOUtil.error(ResultEnum.CATEGORY_NAME_ERROR);
        }
        if (StringUtils.isEmpty(categoryIcon)) {
            return ResultVOUtil.error(ResultEnum.CATEGORY_ICON_ERROR);
        }
        if (blogCategoryService.updateCategory(categoryId,categoryName,categoryIcon)) {
            redisOperator.del(blogCategoryRedisPrefix + categoryId);
            return ResultVOUtil.success();
        } else {
            return ResultVOUtil.error(ResultEnum.CATEGORY_NAME_REPEAT);
        }
    }
}
